<template>
  <div class="private-message-layout">
    <!-- 左侧联系人列表 -->
    <PrivateMessage
        :contacts="contacts"
        @contact-selected="setActiveContact"
        @new-chat="handleNewChat"
    />

    <!-- 右侧聊天窗口 -->
    <PrivateMessageDetail
        v-if="activeContact"
        :current-contact="getCurrentContact"
        :messages="activeMessages"
        :user-id="userId"
        @send-message="handleSendMessage"
    />

    <!-- 未选择联系人时的提示 -->
    <div v-else class="no-contact-selected">
      <div>
        <i class="fas fa-comments"></i>
        <p>选择联系人开始聊天</p>
      </div>
    </div>
  </div>
</template>

<script>
import PrivateMessage from './PrivateMessage.vue';
import PrivateMessageDetail from './PrivateMessageDetail.vue';
import messageApi from '@/api/message';
import { useUserStore } from '@/store/userStore';

export default {
  components: {
    PrivateMessage,
    PrivateMessageDetail
  },
  data() {
    return {
      contacts: [],
      activeContact: null,
      messages: {},
      userId: useUserStore().userId
    };
  },
  computed: {
    getCurrentContact() {
      return this.contacts.find(c => c.id === this.activeContact);
    },
    activeMessages() {
      return this.messages[this.activeContact] || [];
    }
  },
  created() {
    this.fetchPrivateSessions();
  },
  methods: {
    async fetchPrivateSessions() {
      try {
        const res = await messageApi.getPrivateSessions(this.userId);
        this.contacts = res.data.data.map(session => {
          const otherUserId = session.user1Id === this.userId ? session.user2Id : session.user1Id;

          return {
            id: session.sessionId,
            name: `用户${otherUserId}`,
            avatar: `https://randomuser.me/api/portraits/men/${otherUserId % 100}.jpg`,
            lastMessage: session.lastMessage || '暂无消息',
            lastMessageTime: session.lastMessageTime,
            otherUserId
          };
        });
      } catch (error) {
        console.error('获取私信会话失败:', error);
      }
    },

    async setActiveContact(sessionId) {
      this.activeContact = sessionId;
      if (this.messages[sessionId]) return;

      try {
        const res = await messageApi.getPrivateMessages(sessionId, this.userId, 1, 20);
        this.$set(this.messages, sessionId, res.data.data.map(msg => ({
          id: msg.messageId,
          content: msg.content,
          time: new Date(msg.sendTime),
          isSent: msg.senderId === this.userId,
          senderId: msg.senderId
        })));
      } catch (error) {
        console.error('获取私信详情失败:', error);
      }
    },

    async handleSendMessage(content) {
      if (!this.activeContact || !content.trim()) return;

      const contact = this.contacts.find(c => c.id === this.activeContact);
      const receiverId = contact.otherUserId;

      try {
        await messageApi.sendPrivateMessage(this.userId, receiverId, content);

        const newMessage = {
          id: Date.now(),
          content,
          time: new Date(),
          isSent: true,
          senderId: this.userId
        };

        if (!this.messages[this.activeContact]) {
          this.$set(this.messages, this.activeContact, []);
        }
        this.messages[this.activeContact].push(newMessage);

        // 更新会话最后消息
        contact.lastMessage = content;
        contact.lastMessageTime = new Date();
      } catch (error) {
        console.error('发送私信失败:', error);
      }
    },

    handleNewChat() {
      alert('新建聊天功能待实现');
    }
  }
};
</script>

<style scoped>
.private-message-layout {
  display: flex;
  height: calc(100vh - 120px);
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.no-contact-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.no-contact-selected div {
  text-align: center;
  color: #999;
}

.no-contact-selected i {
  font-size: 3rem;
  margin-bottom: 15px;
  color: #dde2e7;
}
</style>
